<template>
  <div class="login">
    <el-row>
      <el-col :xs="16" :sm="6" :md="8" :lg="6" :xl="11">
        <div class="grid-content bg-purple-light">
          <el-form :model="user" :rules="rules" ref="user" class="form">
            <h1 style="text-align: center; padding: 5% 0px;;">Login</h1>
            <el-form-item label="账号" prop="username" label-width="60px">
              <el-input v-model="user.username" placeholder="管理员账号" type="text"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" label-width="60px">
              <el-input v-model="user.password" placeholder="管理员密码" type="password"
                        @keyup.enter.native="submitForm('user')"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('user')">立即登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  login
} from '@/apis/SysApi'

import {
  initRoute
} from '@/router/index'

export default {
  name: 'Login',
  data () {
    return {
      user: {
        username: '',
        password: ''
      },
      rules: {
        username: [{
          required: true,
          message: '请输入管理员账号',
          trigger: 'blur'
        }, {
          min: 5,
          max: 16,
          message: '长度在 5 到 8 个字符',
          trigger: 'blur'
        }
        ],
        password: [{
          required: true,
          message: '请输入管理员密码',
          trigger: 'blur'
        }, {
          min: 8,
          max: 16,
          message: '长度在 8 到 16 个字符',
          trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.user).then(res => {
            sessionStorage.setItem('token', res.data.token)
            sessionStorage.setItem('refreshToken', res.data.refreshToken)
            sessionStorage.setItem('user', this.user.username)
            initRoute()
            this.$router.push('/main')
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.el-row {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login {
  width: 100%;
  height: 100%;
  background-image: linear-gradient(to right, #4e6ef2, #8e71bd);
}

.form {
  border-radius: 10px;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0px;
}

.el-form-item {
  width: 80%;
}

.el-button {
  width: 80%;
  margin-left: 10%;
  background-image: linear-gradient(to left, #4e6ef2, #8e71bd);
}
</style>
